import {createImage, FaceDetector} from '../src';

const resCanvas = document.getElementById('resCanvas') as HTMLCanvasElement;
const resCtx = resCanvas.getContext('2d') as CanvasRenderingContext2D;
const defaultImgPath = 'img/multi_small_face.jpeg';
const fileReader = new FileReader();
const loading = document.getElementById('loading');
const faceDetector = new FaceDetector(undefined, [['landmark68']]);

load();
document.getElementById('uploadImg')!.onchange = function () {
    loadFile(this);
};

async function load() {
    await faceDetector.init();
    run(defaultImgPath);
}

async function run(imgPath: string) {
    loading.style.display = 'block';
    const imgEle = await createImage(imgPath);
    drawImage(imgEle);
    // 预测
    const img_bitmap = await createImageBitmap(imgEle);
    const res = await faceDetector.detect(img_bitmap);
    drawRes(res);
    loading.style.display = 'none';
}

// 绘图
function drawImage(img: HTMLImageElement) {
    const { naturalWidth, naturalHeight } = img;
    resCanvas.width = naturalWidth;
    resCanvas.height = naturalHeight;
    resCtx.drawImage(img, 0, 0, naturalWidth, naturalHeight);
}

// 标记结果
function drawRes(data) {
    resCtx.fillStyle = resCtx.strokeStyle = 'green';
    resCtx.font = '20px';
    resCtx.lineWidth = 2;
    data.forEach(item => {
        const x = item.location.left;
        const y = item.location.top;
        const w = item.location.width;
        const h = item.location.height;
        resCtx.strokeRect(x, y, w, h);
        resCtx.fillText(item.face_probability.toFixed(6), x, y);
        resCtx.beginPath();
        item.landmark68.forEach(({ x, y }) => {
            resCtx.moveTo(x, y);
            resCtx.arc(x, y, 2, 0, 2 * Math.PI);
            resCtx.fill();
        });
    });
}

function loadFile(ipt) {
    if (!ipt.files || !ipt.files[0]) {
        return;
    }
    fileReader.onload = function (evt) {
        if (evt.target && typeof evt.target.result === 'string') {
            run(evt.target.result);
        }
    };
    fileReader.readAsDataURL(ipt.files[0]);
}